package com.blue.blog.api.controller;

import com.blue.blog.api.pojo.Result;
import com.blue.blog.api.pojo.User;
import com.blue.blog.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService service;

    @GetMapping("/users")
    public Result findAllUser() {
        List<User> users = service.findAllUser();

        return Result.ok("查询成功", users);
    }

    @GetMapping("/user")
    public Result findUserByUsernameOrEmail(@RequestParam(required = false) String username, @RequestParam(required = false) String email) {
        if (username == null && email == null) {
            return Result.error("用户名称和邮箱都为空!");
        }

        if (username != null && email != null) {
            return Result.error("用户名称和邮箱都不为空!");
        }

        if (username != null) {
            User user = service.findUserByUsername(username);

            if (user != null) {
                return Result.ok("查询成功!", user);
            } else {
                return Result.ok("用户名称不存在");
            }
        }

        User user = service.findUserByEmail(email);
        if (user != null) {
            return Result.ok("查询成功!", user);
        } else {
            return Result.ok("用户邮箱不存在");
        }
    }

    @PostMapping("/user")
    public Result saveUser(@RequestBody User user) {
        Integer result = service.saveUser(user);

        return Result.ok("注册成功!", result);
    }

    @PutMapping("/user")
    public Result updateUser(@RequestBody User user) {
        Integer result = service.updateUser(user);

        return Result.ok("更新成功!", result);
    }

    @DeleteMapping("/user")
    public Result deleteUserById(@RequestParam Long id) {
        Integer result =  service.deleteUserById(id);

        return Result.ok("删除成功!", result);
    }
}
